package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.base.ResponseResult;
import com.zzyl.constant.CacheConstants;
import com.zzyl.constant.Constants;
import com.zzyl.dto.DeviceDto;
import com.zzyl.dto.DevicePageQueryDto;
import com.zzyl.entity.Device;
import com.zzyl.enums.BasicEnum;
import com.zzyl.enums.DeviceLocationTypeEnum;
import com.zzyl.enums.DevicePhysicalLocationTypeEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.properties.AliIoTConfigProperties;
import com.zzyl.service.DeviceService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.vo.DeviceVo;
import com.zzyl.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    @Autowired(required = false)
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private DeviceMapper deviceMapper;

    //同步数据
    @Override
    public void syncProductList() {
        //请求参数
        QueryProductListRequest request = new QueryProductListRequest();
        request.setPageSize(200);
        request.setCurrentPage(1);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        //调用第三方查询产品列表
        QueryProductListResponse response;
        try {
            response=client.queryProductList(request);
        }catch (Exception e){
            throw new BaseException(BasicEnum.IOT_QUERY_DEVICE_ERROR);
        }
        //判断数据是否为空
         if(!response.getBody().getSuccess()){
              throw  new BaseException(BasicEnum.IOT_QUERY_DEVICE_ERROR);
         }
         //获取数据，存储到redis
       List<QueryProductListResponseBody.QueryProductListResponseBodyDataListProductInfo> productInfo =
               response.getBody().getData().getList().getProductInfo();
    List<ProductVo> collect = productInfo.stream().map(p -> BeanUtil.toBean(p, ProductVo.class)).collect(Collectors.toList());
           redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT, JSONUtil.toJsonStr(collect));
    }
    //查询所有产品列表
    @Override
    public List<ProductVo> allProduct() {
         String s = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT);
         if(EmptyUtil.isNullOrEmpty(s)){
            return Collections.emptyList();
         }
         List<ProductVo> list = JSONUtil.toList(s, ProductVo.class);
          return  list;
    }

    //注册设备
     @Override
     public void registerDevice(DeviceDto deviceDto) {
         //判断设备名称是否重复
         Long aLong = deviceMapper.selectByDeviceName(deviceDto.getDeviceName());
         if ( aLong > 0) {
             throw new BaseException(BasicEnum.DEVICE_NAME_EXIST);
         }
         //iot新增设备
         RegisterDeviceRequest request = deviceDto.getRegisterDeviceRequest();
         request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
         RegisterDeviceResponse response = null;
         try {
             response = client.registerDevice(request);
         } catch (Exception e) {
             throw new BaseException(BasicEnum.IOT_REGISTER_DEVICE_ERROR);
         }
         //接口是否调通
         //接口是否调通
         if(response == null || !response.getBody().success){
             throw new RuntimeException(response.getBody().getErrorMessage());
         }
         //属性拷贝
         Device device = BeanUtil.copyProperties(deviceDto, Device.class);
         device.setIotId(response.getBody().getData().getIotId());
         //产品名称
         //查询产品
         QueryProductRequest queryProductRequest = new QueryProductRequest();
         queryProductRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
         queryProductRequest.setProductKey(deviceDto.getProductKey());
         QueryProductResponse queryProductResponse = null;
         try {
             queryProductResponse = client.queryProduct(queryProductRequest);
         } catch (Exception e) {
             throw new BaseException(BasicEnum.IOT_QUERY_DEVICE_ERROR);
         }
         //设置产品名称
         if (queryProductResponse.getBody().success) {
             device.setProductName(queryProductResponse.getBody().getData().productName);
         }
         //如果设备绑定的位置是随身设备，则把物理绑定位置设置为-1 为老人
         //原因是为了后期方便通过位置字段查询老人数据
         if (device.getLocationType().equals(DeviceLocationTypeEnum.PORTABLE_DEVICE.getOrdinal())) {
             device.setPhysicalLocationType(DevicePhysicalLocationTypeEnum.ELDER.getOrdinal());
         }
         //保存设备到数据库
         try {
             deviceMapper.insertSelective(device);
         } catch (Exception e) {
             //删除iot中的设备数据
             DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
             deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
             deleteDeviceRequest.setIotId(device.getIotId());
             deleteDeviceRequest.setProductKey(device.getProductKey());
             deleteDeviceRequest.setDeviceName(device.getDeviceName());
             DeleteDeviceResponse deleteDeviceResponse = null;
             try {
                 deleteDeviceResponse = client.deleteDevice(deleteDeviceRequest);
             } catch (Exception e1) {
                 throw new BaseException(BasicEnum.IOT_DELETE_DEVICE_ERROR);
             }
             throw new BaseException(BasicEnum.RE_SELECT_PRODUCT);
         }
     }

    @Override
    public PageResponse<DeviceVo> pageQueryDevice(DevicePageQueryDto devicePageQueryDto) {
         PageHelper.startPage(devicePageQueryDto.getPageNum(),devicePageQueryDto.getPageSize());
         Page<DeviceVo> deviceVos = deviceMapper.selectPage(devicePageQueryDto);
         PageResponse<DeviceVo> of = PageResponse.of(deviceVos, DeviceVo.class);
         return  of;
    }

    @Override
    public DeviceVo queryDeviceDetail(QueryDeviceDetailRequest queryDeviceDetailRequest) {
        queryDeviceDetailRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDeviceDetailResponse queryDeviceDetailResponse=null;
        try{
            queryDeviceDetailResponse=client.queryDeviceDetail(queryDeviceDetailRequest);
        }catch (Exception e){
          throw  new BaseException(BasicEnum.IOT_QUERY_DEVICE_ERROR);
        }
        if (EmptyUtil.isNullOrEmpty(queryDeviceDetailResponse) || !queryDeviceDetailResponse.getBody().success) {
            throw new BaseException(BasicEnum.IOT_QUERY_DEVICE_ERROR);
        }
        //第一个是数据库中存储的设备数据，第二个是物联网中的设备数据
        //查询数据库的数据
  DeviceVo deviceVo = deviceMapper.selectByIotId(queryDeviceDetailResponse.getBody().getData().getIotId());
  QueryDeviceDetailResponseBody.QueryDeviceDetailResponseBodyData data = queryDeviceDetailResponse.getBody().getData();
  //CopyOptions.create().ignoreNullValue() 这是设置在data中如果字段值为null的不进入复制
       BeanUtil.copyProperties(data,deviceVo, CopyOptions.create().ignoreNullValue());
        return deviceVo;
    }

    @Override
    public ResponseResult queryThingModelPublished(QueryThingModelPublishedRequest queryDeviceDetailRequest) {
        queryDeviceDetailRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryThingModelPublishedResponse queryThingModelPublishedResponse = null;
        try {
            queryThingModelPublishedResponse = client.queryThingModelPublished(queryDeviceDetailRequest);
             QueryThingModelPublishedResponseBody.QueryThingModelPublishedResponseBodyData data = queryThingModelPublishedResponse.getBody().getData();
             return  ResponseResult.success(data);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.IOT_QUERY_DEVICE_ERROR);
        }
    }

    @Override
    public ResponseResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest queryDeviceDetailRequest) {
        queryDeviceDetailRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse queryDevicePropertyStatusResponse = null;
            try {
                queryDevicePropertyStatusResponse = client.queryDevicePropertyStatus(queryDeviceDetailRequest);
                return ResponseResult.success(queryDevicePropertyStatusResponse.getBody().getData());
            } catch (Exception e) {
                throw new BaseException(BasicEnum.IOT_QUERY_DEVICE_ERROR);
            }
    }

    @Override
    public void deleteDevice(DeleteDeviceRequest deleteDeviceRequest) {
        //在iot上进行删除
         deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
         DeleteDeviceResponse deleteDeviceResponse=null;
         try {
             deleteDeviceResponse = client.deleteDevice(deleteDeviceRequest);
         } catch (Exception e) {
             throw new BaseException(BasicEnum.IOT_DELETE_DEVICE_ERROR);
         }
         if(!deleteDeviceResponse.getBody().getSuccess()){
               throw  new BaseException(BasicEnum.IOT_DELETE_DEVICE_ERROR);
         }
         //在数据库中删除
         deviceMapper.deleteDevice(deleteDeviceRequest.getIotId());
    }
    //修改设备备注名称
    @Override
    public void updateDevice(DeviceDto deviceDto) {
        BatchUpdateDeviceNicknameRequest batchUpdateDeviceNicknameRequest = new BatchUpdateDeviceNicknameRequest();
        batchUpdateDeviceNicknameRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
    }
    //查看指定产品的已发布物模型中的功能定义详情
//    @Override
//    public DeviceVo queryThingModelPublished(QueryDeviceDetailRequest queryDeviceDetailRequest) {
//         String productKey = queryDeviceDetailRequest.getProductKey();
//        return null;
//    }

}
